<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div>
            <span>租户配置</span>
            <p class="header-desc">
              配置当前租户的基础参数，包括微信、支付、AI等第三方服务配置
            </p>
          </div>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 配置类型筛选 -->
        <div class="filter-container">
          <el-select
            v-model="selectedConfigType"
            placeholder="选择配置类型"
            clearable
            @change="handleConfigTypeChange"
            style="width: 200px; margin-right: 10px"
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="(label, value) in configTypes"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
          <!-- <el-button
            type="success"
            @click="handleInitConfigs"
            :disabled="userStore.isTest"
          >
            初始化所有配置
          </el-button> -->
          <el-button
            type="primary"
            @click="handleSaveAll"
            :disabled="userStore.isTest || changedConfigs.size === 0"
          >
            保存所有配置
            <el-badge
              v-if="changedConfigs.size > 0"
              :value="changedConfigs.size"
              class="save-badge"
            />
          </el-button>
        </div>

        <!-- 配置模板快速设置 -->
        <div v-if="!selectedConfigType" class="template-container">
          <h4>必要配置模板</h4>
          <p class="template-tip">
            以下是常用的第三方服务配置模板，请根据业务需要进行配置
          </p>
          <el-row :gutter="20">
            <el-col
              :span="6"
              v-for="(template, type) in configTemplates"
              :key="type"
            >
              <el-card
                class="template-card"
                @click="handleTemplateSelect(type)"
              >
                <div class="template-header">
                  <el-icon class="template-icon">
                    <component :is="getTemplateIcon(type)" />
                  </el-icon>
                  <span class="template-title">{{ configTypes[type] }}</span>
                </div>
                <div class="template-desc">{{ template.description }}</div>
                <div class="template-count">
                  {{ template.configs.length }} 项必填参数
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 配置列表 -->
        <el-table
          :data="displayConfigList"
          border
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column prop="config_type" label="配置类型" width="120">
            <template #default="scope">
              <el-tag :type="getConfigTypeTag(scope.row.config_type)">
                {{
                  configTypes[scope.row.config_type] || scope.row.config_type
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="config_key" label="配置键名" min-width="150" />
          <el-table-column prop="config_value" label="配置值" min-width="250">
            <template #default="scope">
              <el-input
                v-model="scope.row.config_value"
                :type="
                  isEncryptedField(scope.row.config_type, scope.row.config_key)
                    ? 'password'
                    : 'text'
                "
                :show-password="
                  isEncryptedField(scope.row.config_type, scope.row.config_key)
                "
                placeholder="请输入配置值"
                :disabled="userStore.isTest"
                @change="markAsChanged(scope.row)"
                :class="{ 'config-changed': isConfigChanged(scope.row) }"
              />
              <div v-if="isConfigChanged(scope.row)" class="change-tip">
                <el-icon><EditPen /></el-icon>
                <span>已修改，未保存</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="150" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.config_value" type="success"
                >已配置</el-tag
              >
              <el-tag v-else type="warning">未配置</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleSaveSingle(scope.row)"
                :disabled="userStore.isTest || !isConfigChanged(scope.row)"
              >
                保存
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/store/user";
import {
  getTenantConfigs,
  setTenantConfig,
  setTenantConfigsBatch,
  deleteTenantConfig,
  getConfigTypes,
  testTenantConfig,
} from "@/api/tenant-configs";

const userStore = useUserStore();
const loading = ref(false);

// 数据
const configList = ref([]);
const configTypes = ref({});
const predefinedConfigs = ref({});
const selectedConfigType = ref("");
const changedConfigs = ref(new Set()); // 记录已修改的配置

// 预定义配置项（与后端保持一致）
const PREDEFINED_CONFIGS = {
  wechat_mp: {
    app_id: "微信小程序AppID",
    app_secret: "微信小程序AppSecret",
  },
  wechat_pay: {
    mch_id: "商户号",
    api_key: "API密钥",
  },
  wechat_gzh: {
    app_id: "公众号AppID",
    app_secret: "公众号AppSecret",
    token: "Token",
    encoding_aes_key: "EncodingAESKey",
  },
  doubao_ai: {
    api_key: "API密钥",
    model: "模型名称",
  },
  tcos: {
    secret_id: "腾讯云SecretId",
    secret_key: "腾讯云SecretKey",
    region: "地区",
    bucket: "存储桶名称",
  },
};

// 加密字段定义
const ENCRYPTED_FIELDS = {
  wechat_mp: ["app_secret", "api_key"],
  wechat_pay: ["api_key"],
  wechat_gzh: ["app_secret", "encoding_aes_key"],
  doubao_ai: ["api_key"],
  tcos: ["secret_id", "secret_key"],
};

// 配置模板
const configTemplates = ref({
  wechat_mp: {
    description: "微信小程序相关配置",
    configs: [
      {
        key: "app_id",
        description: "小程序AppID",
        required: true,
        encrypted: false,
      },
      {
        key: "app_secret",
        description: "小程序AppSecret",
        required: true,
        encrypted: true,
      },
    ],
  },
  wechat_pay: {
    description: "微信支付相关配置",
    configs: [
      {
        key: "mch_id",
        description: "商户号",
        required: true,
        encrypted: false,
      },
      {
        key: "api_key",
        description: "API密钥",
        required: true,
        encrypted: true,
      },
      {
        key: "cert_path",
        description: "证书路径",
        required: false,
        encrypted: false,
      },
      {
        key: "key_path",
        description: "私钥路径",
        required: false,
        encrypted: false,
      },
    ],
  },
  wechat_gzh: {
    description: "微信公众号相关配置",
    configs: [
      {
        key: "app_id",
        description: "公众号AppID",
        required: true,
        encrypted: false,
      },
      {
        key: "app_secret",
        description: "公众号AppSecret",
        required: true,
        encrypted: true,
      },
      {
        key: "token",
        description: "公众号Token",
        required: true,
        encrypted: false,
      },
      {
        key: "encoding_aes_key",
        description: "EncodingAESKey",
        required: false,
        encrypted: true,
      },
    ],
  },
  doubao_ai: {
    description: "豆包AI相关配置",
    configs: [
      {
        key: "api_key",
        description: "API密钥",
        required: true,
        encrypted: true,
      },
      {
        key: "base_url",
        description: "API地址",
        required: true,
        encrypted: false,
      },
      {
        key: "model",
        description: "模型名称",
        required: true,
        encrypted: false,
      },
    ],
  },
  tcos: {
    description: "腾讯云对象存储相关配置",
    configs: [
      {
        key: "secret_id",
        description: "腾讯云SecretId",
        required: true,
        encrypted: true,
      },
      {
        key: "secret_key",
        description: "腾讯云SecretKey",
        required: true,
        encrypted: true,
      },
      {
        key: "region",
        description: "地区",
        required: true,
        encrypted: false,
      },
      {
        key: "bucket",
        description: "存储桶名称",
        required: true,
        encrypted: false,
      },
    ],
  },
});

// 计算属性 - 显示的配置列表（合并预定义和实际配置）
const displayConfigList = computed(() => {
  const result = [];

  // 遍历所有预定义配置
  Object.keys(PREDEFINED_CONFIGS).forEach((configType) => {
    // 如果选择了特定类型，只显示该类型
    if (selectedConfigType.value && selectedConfigType.value !== configType) {
      return;
    }

    const predefinedKeys = PREDEFINED_CONFIGS[configType];
    Object.keys(predefinedKeys).forEach((configKey) => {
      // 查找是否已有实际配置
      const existingConfig = configList.value.find(
        (config) =>
          config.config_type === configType && config.config_key === configKey
      );

      // 直接使用后端返回的配置值
      let configValue = "";
      if (
        existingConfig &&
        existingConfig.config_value !== null &&
        existingConfig.config_value !== undefined
      ) {
        configValue = String(existingConfig.config_value);
      }

      result.push({
        id: existingConfig?.id,
        config_type: configType,
        config_key: configKey,
        config_value: configValue,
        description: predefinedKeys[configKey],
        is_encrypted: isEncryptedField(configType, configKey),
        created_at: existingConfig?.created_at,
        updated_at: existingConfig?.updated_at,
        // 添加原始值用于比较是否修改
        original_value: configValue,
      });
    });
  });

  return result;
});

// 获取配置类型标签颜色
const getConfigTypeTag = (type) => {
  const typeMap = {
    wechat_mp: "success",
    wechat_pay: "warning",
    wechat_gzh: "primary",
    doubao_ai: "danger",
    tcos: "info",
    system: "info",
    custom: "",
  };
  return typeMap[type] || "";
};

// 判断是否可以测试
const canTest = (configType) => {
  return [
    "wechat_mp",
    "wechat_pay",
    "wechat_gzh",
    "doubao_ai",
    "tcos",
  ].includes(configType);
};

// 判断字段是否需要加密
const isEncryptedField = (configType, configKey) => {
  return ENCRYPTED_FIELDS[configType]?.includes(configKey) || false;
};

// 标记配置已修改
const markAsChanged = (config) => {
  // 不需要额外标记，isConfigChanged会自动检测
  // 但我们仍然保留changedConfigs用于批量保存时的筛选
  const key = `${config.config_type}_${config.config_key}`;
  if (config.config_value !== config.original_value) {
    changedConfigs.value.add(key);
  } else {
    changedConfigs.value.delete(key);
  }
};

// 判断配置是否已修改
const isConfigChanged = (config) => {
  // 比较当前值和原始值
  return config.config_value !== config.original_value;
};

// 保存单个配置
const handleSaveSingle = async (config) => {
  try {
    const res = await setTenantConfig({
      config_type: config.config_type,
      config_key: config.config_key,
      config_value: config.config_value,
      description: config.description,
      is_encrypted: config.is_encrypted,
    });

    if (res.code === 0) {
      ElMessage.success(`配置 ${config.config_key} 保存成功`);
      // 更新原始值，清除修改状态
      config.original_value = config.config_value;
      // 从修改标记中移除
      const key = `${config.config_type}_${config.config_key}`;
      changedConfigs.value.delete(key);
      // 重新获取配置以更新ID等信息
      fetchConfigs();
    } else {
      ElMessage.error(res.message || "保存失败");
    }
  } catch (error) {
    console.error("保存配置失败:", error);
    ElMessage.error("保存失败");
  }
};

// 获取模板图标
const getTemplateIcon = (type) => {
  const iconMap = {
    wechat_mp: "ChatDotRound",
    wechat_pay: "CreditCard",
    wechat_gzh: "Message",
    doubao_ai: "MagicStick",
  };
  return iconMap[type] || "Setting";
};

// 模板选择
const handleTemplateSelect = (type) => {
  selectedConfigType.value = type;
  fetchConfigs();
};

// 获取配置类型列表
const fetchConfigTypes = async () => {
  try {
    console.log("开始获取配置类型...");
    const res = await getConfigTypes();
    console.log("配置类型响应:", res);

    if (res && res.code === 0) {
      configTypes.value = res.data?.types || {};
      predefinedConfigs.value = res.data?.predefined || {};
      console.log("配置类型加载成功:", configTypes.value);
    } else {
      console.error("获取配置类型失败:", res);
      // 使用默认配置类型
      useDefaultConfigTypes();
    }
  } catch (error) {
    console.error("获取配置类型失败:", error);
    // 使用默认配置类型
    useDefaultConfigTypes();
  }
};

// 使用默认配置类型
const useDefaultConfigTypes = () => {
  console.log("使用默认配置类型");
  configTypes.value = {
    wechat_mp: "微信小程序",
    wechat_pay: "微信支付",
    wechat_gzh: "微信公众号",
    doubao_ai: "豆包AI",
    system: "系统配置",
    custom: "自定义配置",
    tcos: "腾讯云对象存储",
  };
};

// 获取配置列表
const fetchConfigs = async () => {
  loading.value = true;
  try {
    console.log("开始获取配置列表...", selectedConfigType.value);
    const res = await getTenantConfigs(selectedConfigType.value);
    console.log("配置列表响应:", res);

    if (res && res.code === 0) {
      const configs = res.data?.configs;
      console.log("后端返回的configs原始数据:", configs);

      // 检查数据格式并转换
      if (Array.isArray(configs)) {
        // 如果是数组格式，直接使用
        configList.value = configs;
        console.log(
          "配置列表加载成功(数组格式):",
          configList.value.length,
          "项"
        );
      } else if (configs && typeof configs === "object") {
        // 如果是对象格式，转换为数组
        const configArray = [];
        Object.keys(configs).forEach((configType) => {
          const typeConfigs = configs[configType];
          if (typeConfigs && typeof typeConfigs === "object") {
            Object.keys(typeConfigs).forEach((configKey) => {
              configArray.push({
                config_type: configType,
                config_key: configKey,
                config_value: typeConfigs[configKey] || "",
                description:
                  PREDEFINED_CONFIGS[configType]?.[configKey] || configKey,
              });
            });
          }
        });
        configList.value = configArray;
        console.log(
          "配置列表加载成功(对象格式转换):",
          configList.value.length,
          "项"
        );
      } else {
        console.warn("返回的configs格式不正确:", configs);
        configList.value = [];
      }

      // 打印每个配置的值
      configList.value.forEach((config) => {
        console.log(
          `配置 ${config.config_type}.${config.config_key} = "${config.config_value}"`
        );
      });
    } else {
      console.error("获取配置失败:", res);
      ElMessage.error(res?.message || "获取配置失败");
      configList.value = []; // 确保是空数组
    }
  } catch (error) {
    console.error("获取配置失败:", error);
    ElMessage.error("获取配置失败，请检查网络连接");
    configList.value = []; // 确保是空数组
  } finally {
    loading.value = false;
    console.log("配置列表加载完成，loading状态已重置");
  }
};

// 刷新数据
const handleRefresh = () => {
  fetchConfigs();
};

// 调试方法
const handleDebug = async () => {
  console.log("=== 开始调试 ===");
  console.log("当前状态:");
  console.log("- loading:", loading.value);
  console.log("- configTypes:", configTypes.value);
  console.log("- configList:", configList.value);
  console.log("- configList是数组吗:", Array.isArray(configList.value));
  console.log("- configList类型:", typeof configList.value);
  console.log("- selectedConfigType:", selectedConfigType.value);
  console.log("- displayConfigList:", displayConfigList.value);
  console.log("- changedConfigs:", changedConfigs.value);

  try {
    // 测试API调用
    console.log("测试获取配置类型...");
    const typesRes = await getConfigTypes();
    console.log("配置类型响应:", typesRes);

    console.log("测试获取配置列表...");
    const configsRes = await getTenantConfigs();
    console.log("配置列表响应:", configsRes);
    console.log("响应中的configs类型:", typeof configsRes?.data?.configs);
    console.log(
      "响应中的configs是数组吗:",
      Array.isArray(configsRes?.data?.configs)
    );

    // 检查配置值
    if (configsRes?.data?.configs) {
      console.log("后端返回的配置详情:");
      configsRes.data.configs.forEach((config) => {
        console.log(
          `- ${config.config_type}.${config.config_key}: 值="${
            config.config_value
          }", 类型=${typeof config.config_value}, 长度=${
            config.config_value?.length
          }`
        );
      });

      console.log("前端显示的配置详情:");
      displayConfigList.value.forEach((config) => {
        console.log(
          `- ${config.config_type}.${config.config_key}: 显示值="${config.config_value}", 原始值="${config.original_value}"`
        );
      });
    }
  } catch (error) {
    console.error("调试过程中出错:", error);
  }

  console.log("=== 调试结束 ===");
};

// 强制停止loading
const forceStopLoading = () => {
  console.log("强制停止loading状态");
  loading.value = false;
  ElMessage.success("Loading状态已重置");
};

// 强制刷新显示
const forceRefreshDisplay = () => {
  console.log("强制刷新显示");
  console.log("当前configList:", configList.value);
  console.log("当前displayConfigList:", displayConfigList.value);

  // 强制触发响应式更新
  const temp = configList.value;
  configList.value = [];
  nextTick(() => {
    configList.value = temp;
    console.log("显示已刷新");
  });
};

// 配置类型变化
const handleConfigTypeChange = () => {
  // 不需要重新获取配置，因为displayConfigList会自动过滤
};

// 初始化所有配置
const handleInitConfigs = async () => {
  ElMessageBox.confirm(
    "确认要初始化所有预定义配置吗？这将为当前租户创建所有必要的配置项（值为空），您可以稍后填写具体的配置值。",
    "初始化配置确认",
    {
      confirmButtonText: "确认初始化",
      cancelButtonText: "取消",
      type: "info",
    }
  ).then(async () => {
    try {
      const allConfigs = [];

      // 收集所有预定义配置
      Object.keys(PREDEFINED_CONFIGS).forEach((configType) => {
        const predefinedKeys = PREDEFINED_CONFIGS[configType];
        Object.keys(predefinedKeys).forEach((configKey) => {
          allConfigs.push({
            config_type: configType,
            config_key: configKey,
            config_value: "", // 空值
            description: predefinedKeys[configKey],
            is_encrypted: isEncryptedField(configType, configKey),
          });
        });
      });

      if (allConfigs.length > 0) {
        const res = await setTenantConfigsBatch(allConfigs);
        if (res.code === 0) {
          ElMessage.success(
            `成功初始化 ${allConfigs.length} 项配置，请填写配置值`
          );
          fetchConfigs();
        } else {
          ElMessage.error(res.message || "初始化失败");
        }
      }
    } catch (error) {
      console.error("初始化配置失败:", error);
      ElMessage.error("初始化失败");
    }
  });
};

// 保存所有配置
const handleSaveAll = async () => {
  if (changedConfigs.value.size === 0) {
    ElMessage.warning("没有需要保存的配置");
    return;
  }

  try {
    const configsToSave = [];

    // 收集所有已修改的配置
    displayConfigList.value.forEach((config) => {
      const key = `${config.config_type}_${config.config_key}`;
      if (changedConfigs.value.has(key)) {
        configsToSave.push({
          config_type: config.config_type,
          config_key: config.config_key,
          config_value: config.config_value,
          description: config.description,
          is_encrypted: config.is_encrypted,
        });
      }
    });

    if (configsToSave.length > 0) {
      const res = await setTenantConfigsBatch(configsToSave);
      if (res.code === 0) {
        ElMessage.success(`成功保存 ${configsToSave.length} 项配置`);
        changedConfigs.value.clear(); // 清除修改标记
        fetchConfigs(); // 重新获取配置
      } else {
        ElMessage.error(res.message || "保存失败");
      }
    }
  } catch (error) {
    console.error("保存配置失败:", error);
    ElMessage.error("保存失败");
  }
};

// 测试配置
const handleTest = async (configType) => {
  try {
    const res = await testTenantConfig(configType);
    if (res.code === 0) {
      ElMessage.success(res.message || "测试通过");
    } else {
      ElMessage.error(res.message || "测试失败");
    }
  } catch (error) {
    console.error("测试配置失败:", error);
    ElMessage.error("测试失败");
  }
};

onMounted(() => {
  console.log("组件挂载，开始初始化...");
  // 先获取配置类型（不影响loading状态）
  fetchConfigTypes();
  // 再获取配置列表（会管理loading状态）
  fetchConfigs();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-desc {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 13px;
  line-height: 1.4;
}

.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.encrypted-value {
  color: #909399;
  font-style: italic;
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.template-container {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.template-container h4 {
  margin: 0 0 8px 0;
  color: #303133;
}

.template-tip {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 13px;
}

.template-card {
  cursor: pointer;
  transition: all 0.3s ease;
  height: 120px;
}

.template-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.template-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.template-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #409eff;
}

.template-title {
  font-weight: 600;
  color: #303133;
}

.template-desc {
  color: #606266;
  font-size: 12px;
  margin-bottom: 8px;
}

.template-count {
  color: #909399;
  font-size: 11px;
}

/* 配置修改提示样式 */
.config-changed {
  border-color: #e6a23c !important;
}

.change-tip {
  display: flex;
  align-items: center;
  margin-top: 4px;
  color: #e6a23c;
  font-size: 12px;
}

.change-tip .el-icon {
  margin-right: 4px;
  font-size: 12px;
}

/* 保存按钮徽章样式 */
.save-badge {
  margin-left: 8px;
}
</style>
